package com.mbiolance.cloud.activiti.common.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mbiolance.cloud.auth.domain.R;
import com.mbiolance.cloud.auth.domain.dto.SysUserDto;
import com.mbiolance.cloud.auth.rpc.SysUserFeignService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component("mbiolanceTaskListener")
public class TaskListenerImpl implements TaskListener {

    @Autowired
    private SysUserFeignService sysUserFeignService;

    private Expression paramsJson;

    @Override
    public void notify(DelegateTask delegateTask) {
        Object paramsJsonObj = paramsJson.getValue(delegateTask);
        if (paramsJsonObj == null) {
            return;
        }
        JSONObject json = new JSONObject();
        try {
            json = JSON.parseObject(String.valueOf(paramsJsonObj));
        } catch (Exception e) {
            log.error("TaskListenerImpl get paramsJson error: {}", e.getMessage());
        }
        String assgineeRole = json.getString("assgineeRole");
        if (StrUtil.isNotEmpty(assgineeRole)) {
            List<SysUserDto> data = Optional.ofNullable(sysUserFeignService.listByRole(assgineeRole)).orElse(new R<>()).getData();
            // 根据角色获取用户信息, 将获取到的用户设置到任务的候选人中
            if (CollectionUtil.isNotEmpty(data)) {
                delegateTask.addCandidateUsers(data.stream()
                        .map(v -> String.valueOf(v.getId())).collect(Collectors.toList()));
            }
        }
        delegateTask.setVariable("paramsJsonObj", paramsJsonObj);
    }
}
